<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    img {
      display: block;
      margin-bottom: 50px;
      height: 200px;
      width: 400px;
    }
  </style>
  <body>
    <!-- IntersectionObserver -->
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <img src="./260.jpg" data-src="./360.jpg" />
    <script>
      const imgs = document.querySelectorAll('img[data-src]')
      const config = {
        rootMargin: '0px',
        threshold: 0,
      }
      let observer = new IntersectionObserver((entries, self) => {
        // console.log(entries) //刚刚进入可视区域的
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            let img = entry.target // img Dom
            let src = img.dataset.src // 实际的url
            if (src) {
              img.src = src
              img.removeAttribute('data-src')
            }
            // 解除观察
            console.log(self)
            self.unobserve(entry.target)
          }
        })
      }, config)

      imgs.forEach((image) => {
        observer.observe(image) // 开始观察每一项
      })
    </script>
  </body>
</html>
